// Use an object to encapsulate logic and clear up global namespace
var game = 
{
    playerWins: 0,
    computerWins: 0,
    playerMove: true,
    playerImage: 
    {
        src: "x.png"
    },
    computerImage: 
    {
        src: "o.png"
    },

    // Represents the game board using characters
    board: [],

    // Characters for the board
    UNOCCUPIED: ' ',
    HUMAN: 'X',
    COMPUTER: 'O',

    BOARD_SIZE: 9
};

game.NewGame = function () 
{
    for (var i = 0; i < game.BOARD_SIZE; i++) 
    {
        game.board[i] = game.UNOCCUPIED;
        document.images[i].src = "blank.png";
    }

    game.playerMove = true;
    game.ShowInfo("Your turn.", "human");

    $('#board-background').css('z-index', -1);
}

game.ShowInfo = function (info, className) 
{
    $("#turnInfo").removeClass();   // Remove all
    if (className !== undefined)
        $("#turnInfo").addClass(className);

    $("#turnInfo").html(info);
}

game.MakeMove = function (e) 
{
    // Determine the position by chopping off "pos" from the image's id 
    pos = parseInt(e.target.getAttribute("id").substr(3));

    // Make sure it's the human's move and the position isn't already occupied
    if (game.playerMove && game.board[pos] == game.UNOCCUPIED) 
    {
        game.board[pos] = game.HUMAN;
        imageId = '#' + e.target.getAttribute("id");
        $(imageId).hide().attr("src", game.playerImage.src).show('normal');
        //e.target.src = game.playerImage.src;
        game.playerMove = !game.playerMove;

        // If the game's not over, make computer move in one second 
        if (!game.GameOver()) 
        {
            game.ShowInfo("Computer's turn.", "computer");
            timerId = setInterval(game.MakeComputerMove, 1000);
        }
    }
}

game.MakeComputerMove = function () 
{
    clearInterval(timerId);

    // Generate random move, but keep count of how many times we try so we avoid
    // accidentally getting stuck in the loop.
    var count = 0;
    var move;
    do 
    {
        move = Math.floor(Math.random() * game.BOARD_SIZE);
        count++;
    } while ((game.board[move] == game.HUMAN || game.board[move] == game.COMPUTER) && count < 100);

    if (count == 100)
        alert("There's something wrong... computer can't find an open move.");
    else 
    {
        game.board[move] = game.COMPUTER;
        //document.images[move].src = game.computerImage.src;
        var imageId = "#pos" + move;
        $(imageId).hide().attr("src", game.computerImage.src).show('normal');
    }

    if (!game.GameOver()) 
    {
        game.playerMove = !game.playerMove;
        game.ShowInfo("Your turn.", "human");
    }
}

// Draw a line from the start location to the end location on the board.
game.DrawLine = function (start, end) 
{
    // Convert start and end into (x,y) canvas coordinates
    var x1, x2;

    if (start == 0 || start == 3 || start == 6)
        x1 = 40;
    else if (start == 1 || start == 4 || start == 7)
        x1 = 135;
    else
        x1 = 230;

    if (start >= 0 && start <= 2)
        y1 = 40;
    else if (start >= 3 && start <= 5)
        y1 = 135;
    else
        y1 = 230;

    if (end == 0 || end == 3 || end == 6)
        x2 = 40;
    else if (end == 1 || end == 4 || end == 7)
        x2 = 135;
    else
        x2 = 230;

    if (end >= 0 && end <= 2)
        y2 = 40;
    else if (end >= 3 && end <= 5)
        y2 = 135;
    else
        y2 = 230;


    var canvas = document.getElementById("board-background");
    var context = canvas.getContext("2d");

    $('#board-background').hide();

    // Bring to the front
    canvas.style.zIndex = 3;

    // Clear off any previous lines
    context.clearRect(0, 0, canvas.width, canvas.height)

    // Draw line
    context.beginPath();     // Restarts line
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.strokeStyle = "black";
    context.lineWidth = "6";
    context.stroke();

    $('#board-background').fadeIn('slow');
}

// Check for a winner.  Return an array with this format: [status, first_pos, last_pos]
//   status:
//     0 if no winner or tie yet
//     1 if it's a tie
//     2 if X won
//     3 if O won
//   first_pos: Position of the first X or O winning move
//   last_pos:  Position of the last X or O winning move
//
//   Example: [2, 0, 3] would indicate X won with an X in position 0 and 3.
game.CheckForWinner = function () 
{
    // Check for horizontal wins
    for (i = 0; i <= 6; i += 3) {
        if (game.board[i] == game.HUMAN && game.board[i + 1] == game.HUMAN && game.board[i + 2] == game.HUMAN)
            return [2, i, i + 2];
        if (game.board[i] == game.COMPUTER && game.board[i + 1] == game.COMPUTER && game.board[i + 2] == game.COMPUTER)
            return [3, i, i + 2];
    }

    // Check for vertical wins
    for (i = 0; i <= 2; i++) 
    {
        if (game.board[i] == game.HUMAN && game.board[i + 3] == game.HUMAN && game.board[i + 6] == game.HUMAN)
            return [2, i, i + 6];
        if (game.board[i] == game.COMPUTER && game.board[i + 3] == game.COMPUTER && game.board[i + 6] == game.COMPUTER)
            return [3, i, i + 6];
    }

    // Check for diagonal wins
    if (game.board[0] == game.HUMAN && game.board[4] == game.HUMAN && game.board[8] == game.HUMAN)
        return [2, 0, 8];

    if (game.board[2] == game.HUMAN && game.board[4] == game.HUMAN && game.board[6] == game.HUMAN)
        return [2, 2, 6];

    if (game.board[0] == game.COMPUTER && game.board[4] == game.COMPUTER && game.board[8] == game.COMPUTER)
        return [3, 0, 8];

    if (game.board[2] == game.COMPUTER && game.board[4] == game.COMPUTER && game.board[6] == game.COMPUTER)
        return [3, 2, 6];

    // Check for tie
    for (i = 0; i < game.BOARD_SIZE; i++) 
    {
        // If we find a number, then no one has won yet
        if (game.board[i] != game.HUMAN && game.board[i] != game.COMPUTER)
            return [0];
    }

    // If we make it through the previous loop, all places are taken, so it's a tie
    return [1];
}

game.UpdateWins = function () 
{
    //document.getElementById("playerWins").innerHTML = game.playerWins;
    //document.getElementById("computerWins").innerHTML = game.computerWins;	

    $('#playerWins').html(game.playerWins);
    $('#computerWins').html(game.computerWins);
}

// Returns true if game is over and outputs appropriate ending message, otherwise returns false.
game.GameOver = function ()
{
    var ret = game.CheckForWinner();

    if (ret[0] == 1)
        game.ShowInfo("It's a tie!");
    else if (ret[0] == 2) 
    {
        game.ShowInfo("You won!");
        game.playerWins++;
        game.UpdateWins();
        game.DrawLine(ret[1], ret[2]);
        window.localStorage.setItem("playerWins", game.playerWins);
    }
    else if (ret[0] == 3) 
    {
        game.ShowInfo("The computer won!");
        game.computerWins++;
        game.UpdateWins();
        game.DrawLine(ret[1], ret[2]);
        window.localStorage.setItem("computerWins", game.computerWins);
    }
    else
        return false;

    return true;
}

game.ClearWins = function () 
{
    if (confirm("Are you sure you want to reset the win scores?"))
     {
        window.localStorage.clear();
        game.playerWins = 0;
        game.computerWins = 0;
        game.UpdateWins();
    }
}

$(document).ready(function () 
{
    $('#newgame').click(game.NewGame);
    $('#resetWins').click(game.ClearWins);
    $('img[id^="pos"]').click(game.MakeMove);

    // getItem returns null if key is not found
    game.playerWins = window.localStorage.getItem("playerWins") || 0;
    game.computerWins = window.localStorage.getItem("computerWins") || 0;
    game.UpdateWins();

    game.NewGame();
});

//window.addEventListener("load", game.init, false);


